//
//  NetworkTools.swift
//  AF-Tool
//
//  Created by 叶子韬韬 on 2017/4/30.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import UIKit
import AFNetworking
enum RequestTppe {
    case get
    case post
}
class NetworkTools: AFHTTPSessionManager {

    //let 在swift中是线程安全的   单例
    static let shareInstance :NetworkTools = {
        let tools = NetworkTools();
        

        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

//        tools.requestSerializer.timeoutInterval = 30
        
        return tools
    }()
    
}
// MARK:- #注释> 封装请求方法
extension NetworkTools{
    
  
    
    func request(methodType:RequestTppe,urlString:String,parameters: [String:Any], finished:@escaping(_ result:Any?,_ error:Error?)->()) {

        
        //1 定义成功的回调闭包
        let successCallBack = { (task:URLSessionDataTask, result:Any?)-> Void in
            finished(result, nil)
        }
        
        //2 定义失败的回调闭包
        
        let failCallBack = {(task:URLSessionDataTask?, error:Error?)-> Void in
        finished(nil, error)
        }
        
        if methodType == .get{
          
            get(urlString, parameters: parameters, progress: nil, success: successCallBack as (URLSessionDataTask, Any?) -> Void, failure: failCallBack)
            
        }else if methodType == .post{
            
            post(urlString, parameters: parameters, progress: nil, success: successCallBack as (URLSessionDataTask, Any?) -> Void, failure: failCallBack)
            
        }
        
    }
}

// MARK:- #注释>请求AccessToken
extension NetworkTools{
    func loadAccessToken(code:String,finised:@escaping (_ result:[String:Any]?,_ error:Error?) -> ()) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let parameter = ["client_id":app_key,"client_secret":app_secret,"grant_type":"authorization_code","redirect_uri":redirect_uri,"code":code]
        
        request(methodType: .post, urlString: url, parameters: parameter as [String : Any]) { (result:Any?, error:Error?) in
        
        
            finised(result as? [String : Any], error)
        
 
        }
        
        
    }
}
// MARK:- #注释>请求用户个人信息
extension NetworkTools{
    internal func loadUserInfo(access_token:String,uid:String,finished:@escaping (_ result:[String:Any]?,_ error:Error?) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let paramter = ["access_token":access_token,"uid":uid]
        
        request(methodType: .get, urlString: urlString, parameters: paramter) { (result, error) in
            finished(result as? [String : Any], error)
        }
        
        
    }
}
// MARK:- #注释>请求首页数据
extension NetworkTools{
    func loadStatus(max_id:Int,since_id:Int,finised:@escaping (_ result:[[String: Any]]?,_ error:Error?) -> ()){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //请求参数
        let paramter = ["access_token":(UserAccoutViewModel.shareInstance.account?.access_token)!,"since_id":"\(since_id)","max_id":"\(max_id)"]
        
        request(methodType: .get, urlString: urlString, parameters: paramter) { (result, error) in
            
            //先去字典
           guard let resultDict = result as? [String : Any] else{
                finised(nil, error)
                return
            }
            //将数组数据回调给外界的控制器
            finised(resultDict["statuses"] as? [[String : Any]], error)
        }
        
    }
}
// MARK:- #注释>发送微博
extension NetworkTools {
    func sendStatus(statusText:String,isSuccess:@escaping (_ isSuccess:Bool)->())  {
        let usrString = "https://api.weibo.com/2/statuses/update.json"
        
        let parameters = ["access_token":(UserAccoutViewModel.shareInstance.account?.access_token)!,"status":statusText]
        
        request(methodType: .post, urlString: usrString, parameters: parameters) { (result, error) in
            if result != nil{
                isSuccess(true)
            }else{
                isSuccess(false)
            }
        }
        
        
    }
}
// MARK:- #注释>发送微博携带照片
extension NetworkTools {
    
    func sendStatus(statusText:String,image:UIImage,isSuccess:@escaping (_ isSuccess:Bool)->())  {
        let usrString = "https://api.weibo.com/2/statuses/upload.json"
        
        let parameters = ["access_token":(UserAccoutViewModel.shareInstance.account?.access_token)!,"status":statusText]
        
      self.post(usrString, parameters: parameters, constructingBodyWith: { (fromData) in
        
        if let imageData = UIImageJPEGRepresentation(image, 0.5){
            fromData.appendPart(withFileData: imageData, name: "pic", fileName: "sasa", mimeType: "image/jpg")
        }
    
      }, progress: nil, success: { (_, _) in
        isSuccess(true)
      }) { (_, error) in
        print(error)
        }
        
    }

}
